﻿using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.RM.DataAccess;
using WP.RM.DataEntity;

namespace WP.RM.BusinessRule
{
    public class RMProductBOMSalesBRL : RuleBase 
    {


        public bool InitProductBOMRev(DBAccess dbcon, DataRow drBOMHdr, string strProductFItemID, string strCategoryID, string strSetID, string strTechnicsName, string strVisionNo)
        {
            try
            {
                string strSQL="";
                // init HDR
                            

                //string strVisionNo = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue(dbcon, "rmProductBOMSales", "max(VersionNo)", " productname='"+ strProductName +"'")) + 1);
                RMProductBOMSalesDAL rmBOM = new RMProductBOMSalesDAL();
                strSQL = "select A.*  from rmProductBOMDetail A  where A.CategoryID='{0}' and A.SetID='{1}' and A.ProductFItemID='{2}' and A.TechnicsName ='{3}'  order by A.RowSeqNo";
                strSQL = string.Format(strSQL, strCategoryID, strSetID,strProductFItemID,strTechnicsName);
                DataTable dtOld = dbcon.GetDataTable(strSQL);
                foreach (DataRow dr in dtOld.Rows)
                {
                    DataRow drBOM = dbcon.GetDataSet("select * from rmProductBOMDetailSales").Tables[0].NewRow();

                    drBOM["SeqNo"] = dr["SeqNo"].ToString().TrimEnd();
                    drBOM["RowSeqNo"] = dr["RowSeqNo"].ToString().Trim();
                    drBOM["WKID"] = dr["WKID"].ToString(); 
                    drBOM["WKName"] = dr["WKName"].ToString().TrimEnd();
                    drBOM["VersionNo"] = strVisionNo;
                    drBOM["ProductFItemID"] = strProductFItemID;
                    drBOM["ProductName"] = DataFunctions.GetFieldValue(dbcon, "rmProduct", "ProductName", " ProductFItemID='" + dr["ProductFItemID"] + "'");
                    drBOM["TechnicsName"] = dr["TechnicsName"].ToString().TrimEnd();  

                    drBOM["CategoryID"] = dr["CategoryID"].ToString().TrimEnd();
                    drBOM["SetID"] = CvtFunc.ToString(dr["SetID"]);

                    drBOM["CategoryName"] = DataFunctions.GetFieldValue(dbcon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                    drBOM["SetName"] = DataFunctions.GetFieldValue(dbcon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                    
                    drBOM["FItemID"] = CvtFunc.ToString(dr["FItemID"]);
                    drBOM["ItemNo"] = DataFunctions.GetFieldValue(dbcon, "iminvmaster", "itemno", "FItemID='" + dr["FItemID"] + "'");
                    drBOM["ItemName"] = DataFunctions.GetFieldValue(dbcon, "iminvmaster", "itemname", "FItemID='" + dr["FItemID"] + "'");;
                    drBOM["SupNo"] = CvtFunc.ToString(dr["SupNo"]);
                    drBOM["SupName"] = CvtFunc.ToString(dr["SupName"]);
                    drBOM["LabourCost"] = BaseFunctions.FormatNumeric(dr["LabourCost"], "Ns.8");
                    //drBOM["Price"] = BaseFunctions.FormatNumeric(dr["Price"], "Ns.8");
                    drBOM["Price"] = CvtFunc.ToDouble(DataFunctions.GetFieldValue(dbcon, "iminvmaster", "MarketCost", "FItemID='" + drBOM["FItemID"].ToString() + "' "));
                    drBOM["PriceUnit"] = CvtFunc.ToString(dr["PriceUnit"]);
                    drBOM["Qty"] = BaseFunctions.FormatNumeric( CvtFunc.ToDouble (dr["Qty"]).ToString ("F8"), "Ns.8");
                    drBOM["QtyWastage"] = BaseFunctions.FormatNumeric(dr["QtyWastage"], "Ns.8");
                    drBOM["WastageRate"] = BaseFunctions.FormatNumeric(dr["WastageRate"], "Ns.8");
                    drBOM["TotalCost"] = BaseFunctions.FormatNumeric(dr["TotalCost"], "Ns.8");
                    drBOM["DetailCost"] = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.8");
                    drBOM["IsInputWK"] = dr["IsInputWK"].ToString();
                    drBOM["IsKeyWK"] = dr["IsKeyWK"].ToString();
                    //if (!rmBOM.UpdateBOMDetail(dbcon, drBOM))
                    //{
                    //    return false;
                    //}
                    if (dr != dtOld.Rows[dtOld.Rows.Count-1])
                    {
                        if (!rmBOM.UpdateBOMDetail(dbcon, drBOM, true))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (!rmBOM.UpdateBOMDetail(dbcon, drBOM, false ))
                        {
                            return false;
                        }
                    }
                    // Init  rmWKProductFormula from rmWKFormula
                    strSQL = "select * from rmWKProductFormula where BOMRecID='" + CvtFunc.ToString(dr["RecID"]) + "'";
                    DataTable dtFormula = dbcon.GetDataTable(strSQL);
                    foreach (DataRow drFormula in dtFormula.Rows)
                    {
                        strSQL = @"Insert Into rmWKProductFormulaSales (BOMRecID,ProductName,WKFormula)
                              VALUES ('{0}','{1}','{2}')";
                        strSQL = string.Format(strSQL, drBOM["RecID"], drBOM["ProductName"], drFormula["WKFormula"]);
                        dbcon.ExecuteSql(strSQL);
                    }
                    if (dr != dtOld.Rows[dtOld.Rows.Count - 1])
                    {
                        if (!rmBOM.UpdateBOMDetail(dbcon, drBOM, true))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (!rmBOM.UpdateBOMDetail(dbcon, drBOM, false))
                        {
                            return false;
                        }
                    }
                }

                strSQL = "select A.* from rmProductBOMLabourCost A where A.CategoryID='{0}' and A.SetID='{1}' and A.ProductFItemID='{2}' and A.TechnicsName='{3}' order by a.RowSeqNo ";
                strSQL = string.Format(strSQL, strCategoryID, strSetID,strProductFItemID, strTechnicsName );
                dtOld = dbcon.GetDataTable(strSQL);
                foreach (DataRow dr in dtOld.Rows)
                {
                    DataRow drBOM = dbcon.GetDataSet("select * from rmProductBOMLabourCostSales").Tables[0].NewRow();

                    drBOM["SeqNo"] = dr["SeqNo"].ToString().TrimEnd();
                    drBOM["RowSeqNo"] = dr["RowSeqNo"].ToString().Trim();
                    drBOM["WKID"] = dr["WKID"].ToString().TrimEnd();
                    drBOM["WKName"] = dr["WKName"].ToString().TrimEnd();
                    drBOM["WKOutName"] = dr["WKOutName"].ToString().TrimEnd();
                    drBOM["ProductFItemID"] = strProductFItemID;
                    drBOM["ProductName"] = DataFunctions.GetFieldValue(dbcon, "rmProduct", "ProductName", " ProductFItemID='" + dr["ProductFItemID"] + "'");
                    drBOM["TechnicsName"] = dr["TechnicsName"].ToString().TrimEnd();

                    drBOM["CategoryID"] = dr["CategoryID"].ToString().TrimEnd();
                    drBOM["SetID"] = CvtFunc.ToString(dr["SetID"]);

                    drBOM["CategoryName"] = DataFunctions.GetFieldValue(dbcon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                    drBOM["SetName"] = DataFunctions.GetFieldValue(dbcon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                    drBOM["VersionNo"] = strVisionNo;
                    drBOM["CalUnit"] = CvtFunc.ToString(dr["CalUnit"]);
                    drBOM["CutType"] = CvtFunc.ToString(dr["CutType"]);
                    drBOM["TotalQty"] = BaseFunctions.FormatNumeric(dr["TotalQty"], "Ns.6");
                    drBOM["StandardQty"] = BaseFunctions.FormatNumeric(dr["StandardQty"], "Ns.8");
                    drBOM["SpendHours"] = CvtFunc.ToString(dr["SpendHours"]);
                    drBOM["StandardWage"] = BaseFunctions.FormatNumeric(dr["StandardWage"], "Ns.8");
                    drBOM["StandardWage26"] = BaseFunctions.FormatNumeric(dr["StandardWage26"], "Ns.8");
                    drBOM["UnitCost"] = BaseFunctions.FormatNumeric(dr["UnitCost"], "Ns.8");
                    drBOM["Remark"] = CvtFunc.ToString(dr["Remark"]);
                    drBOM["WorkCost"] = CvtFunc.ToString(dr["WorkCost"]);
                    drBOM["FItemID"] = CvtFunc.ToString(dr["FItemID"]);
                    drBOM["ItemNo"] = DataFunctions.GetFieldValue(dbcon, "iminvmaster", "itemno", "FItemID='" + dr["FItemID"] + "'");
                    drBOM["IsKeyWK"] = CvtFunc.ToBoolean(dr["IsKeyWK"]);
                    //if (!rmBOM.UpdateLabourCostDetail(dbcon, drBOM))
                    //{
                    //    return false;
                    //}
                    if (dr != dtOld.Rows[dtOld.Rows.Count-1])
                    {
                        if (!rmBOM.UpdateLabourCostDetail(dbcon, drBOM, true ))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (!rmBOM.UpdateLabourCostDetail(dbcon, drBOM, false))
                        {
                            return false;
                        }
                    }
                    // Init  rmWKProductFormula from rmWKFormula
                    strSQL = "select * from rmWKFormulaOtherProductBOM where BOMRecID='" + CvtFunc.ToString(dr["RecID"]) + "'";
                    DataTable dtFormula = dbcon.GetDataTable(strSQL);
                    foreach (DataRow drFormula in dtFormula.Rows)
                    {
                        strSQL = @"Insert Into rmWKFormulaOtherProductBOMSales (BOMRecID,ProductName,WKFormula)
                              VALUES ('{0}','{1}','{2}')";
                        strSQL = string.Format(strSQL, drBOM["RecID"], drBOM["ProductName"], drFormula["WKFormula"]);
                        dbcon.ExecuteSql(strSQL);
                    }
                    if (dr != dtOld.Rows[dtOld.Rows.Count - 1])
                    {
                        if (!rmBOM.UpdateLabourCostDetail(dbcon, drBOM, true))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (!rmBOM.UpdateLabourCostDetail(dbcon, drBOM, false))
                        {
                            return false;
                        }
                    }
                }                
                return true;
            }
            catch (Exception ex)
            {
                MsgBoxEx.Show(ex.ToString()); 
                return false;
            }

        }
        #region Insert Valid
        public bool InsertValid(DBAccess dBAccess, RMProductBOMSalesDEL rmProductDEL)
        {
            bool bReturn = true;
            string strErrPrompt = string.Empty;
            SysVar.ErrorMessage.Clear();

            DataView dvwCheck = dBAccess.GetDataTable("select * from mnamedict where NeedCheck=1 and tablename='" + RMProductBOMSalesDEL.TABLENAME_RMProductRev + "'").DefaultView;
            foreach (DataRowView drw in dvwCheck)
            {
                if (!FieldCheck(dBAccess, rmProductDEL.Tables[RMProductBOMSalesDEL.TABLENAME_RMProductRev].Rows[0], drw["FieldName"].ToString(), ref strErrPrompt, FormStatus.AddNew))
                {
                    bReturn = false;
                    if (SysVar.ErrorMessage.Count == 0)
                    {
                        SysVar.ErrorMessage.Add(new ErrInfo(strErrPrompt, drw["FieldName"].ToString()));
                    }
                    break;
                }
            }
            return bReturn;
        }
        #endregion

        #region Update Valid
        public bool UpdateValid(DBAccess dBAccess, RMProductBOMSalesDEL RMProductDEL)
        {
            bool bReturn = true;
            string strErrPrompt = string.Empty;
            SysVar.ErrorMessage.Clear();

            if (IsExistedAndNotChanged(dBAccess, RMProductDEL.Tables[RMProductBOMSalesDEL.TABLENAME_RMProductRev]))
            {
                DataView dvwCheck = dBAccess.GetDataTable("select * from mnamedict where NeedCheck=1 and tablename='" + RMProductBOMSalesDEL.TABLENAME_RMProductRev + "'").DefaultView;
                foreach (DataRowView drw in dvwCheck)
                {
                    if (!FieldCheck(dBAccess, RMProductDEL.Tables[RMProductBOMSalesDEL.TABLENAME_RMProductRev].Rows[0], drw["FieldName"].ToString(), ref strErrPrompt, FormStatus.Update))
                    {
                        bReturn = false;
                        if (SysVar.ErrorMessage.Count == 0)
                        {
                            SysVar.ErrorMessage.Add(new ErrInfo(strErrPrompt, drw["FieldName"].ToString()));
                        }
                        break;
                    }
                }
            }
            else
            {
                bReturn = false;
            }
            return bReturn;
        }
        #endregion

        #region Delete Valid
        public bool DeleteValid(DBAccess dBAccess, string strRecId, byte[] btOldRecStamp)
        {
            SysVar.ErrorMessage.Clear();

            if (!base.IsExistedAndNotChanged(dBAccess, "rmProductBOMSales", strRecId, btOldRecStamp))
                return false;
            if (MsgBoxEx.Show(Msg.Select("您确定要删除此记录?", DataFunctions.GetMsg("SureToDeleteThisRecord")), SysVar.ConfirmTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region Field Check
        public bool FieldCheck(DBAccess dbcon, DataRow dr, string strFieldName, ref string strErrPrompt, FormStatus formStatus)
        {
            strErrPrompt = string.Empty;
            if (strFieldName == null) return true;

            bool blnExistsField = false;
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                if (dr.Table.Columns[i].Caption.ToUpper().Trim() == strFieldName.Trim().ToUpper())
                {
                    blnExistsField = true;
                    break;
                }
            }
            if (!blnExistsField) return true;
            string strFieldValue = CvtFunc.ToString(dr[strFieldName.Trim()]);

            switch (strFieldName.ToUpper().Trim())
            {
               
                default:
                    return RuleBase.FieldValueCheckOne(dbcon, strFieldValue, RMProductBOMSalesDEL.TABLENAME_RMProductRev , strFieldName, ref strErrPrompt);
            }
        }
        #endregion


        public bool DeleteDetailValid(DBAccess dbcon, string strRecID)
        {
            return true;
        }
        public bool DeleteDetailValid_LabourCost(DBAccess dbcon, string strRecID)
        {
            return true;
        }
    }
}
